import 'package:example/app/data/model/article_bean.dart';
import 'package:example/app/data/model/hot_keywords_bean.dart';
import 'package:example/app/data/model/page_bean.dart';
import 'package:example/app/data/repository/wan_android_repository.dart';
import 'package:example/index.dart';
import 'package:flutter/material.dart';
class SearchController extends BaseViewModel{

  static final String kKeywords = 'kKeywords';

  late TextEditingController searchController;

  /// 搜索的关键字
  final keywords = ''.obs;

  /// 是否显示搜索后的结果
  final RxBool showContent = false.obs;

  /// 搜索历史记录
  List<dynamic> searchHistory = [];

  /// 搜索热词
  List<HotKeywordsBean> hotKeywords = [];

  /// 文章列表
  List<ArticleBean> articles = <ArticleBean>[];

  RefreshController refreshController = RefreshController(initialRefresh: false);
  int currentPage = 0;

  @override
  void onInit() {
    searchController = TextEditingController();
    super.onInit();
  }

  @override
  void onReady()async{
    super.onReady();

    /// 输入结束后执行搜索
    debounce(keywords, (_)async{
      /// 保存查询的key
      saveKeywordsHistory();

      if(keywords.value.isNotEmpty){
        showContent.value = true;
      }else{
        showContent.value = false;
      }
      /// 请求查询
      setBusy();
      await onRefresh();
    }, time: Duration(seconds: 1));
    /// 获取搜索历史
    getKeywordsHistory();
    /// 获取搜索热词
    getHotkey();
  }

  // 获取搜索历史
  void getKeywordsHistory(){
    var keywords = StorageManager.localStorage.getItem(kKeywords);
    if(keywords is List) {
      this.searchHistory = keywords;
    }else{
      this.searchHistory = [];
    }
    update();
  }
  /// 添加搜索历史
  void saveKeywordsHistory(){
    if(keywords.value.isEmpty) return;
    if(searchHistory.contains(keywords.value)){
      searchHistory.remove(keywords.value);
    }
    List<dynamic> ks = [keywords.value, ...searchHistory];
    this.searchHistory = ks;
    update();
    StorageManager.localStorage.setItem(kKeywords, ks);
  }
  /// 删除某个搜索历史
  void delHistoryItem(String item){
    searchHistory.remove(item);
    this.searchHistory = searchHistory;
    update();
    StorageManager.localStorage.setItem(kKeywords, searchHistory);
  }
  /// 清空搜索历史
  void cleanHistory(){
    this.searchHistory = [];
    update();
    StorageManager.localStorage.deleteItem(kKeywords);
  }
  /// 获取搜索热词
  void getHotkey()async{
    try{
      var list = await WanAndroidRepository.getHotkey();
      hotKeywords = list;
      update();
    }catch(e,s){
      handlerError(e, s);
    }
  }

  /// 加载数据
  Future<PageBean<ArticleBean>?>? loadData()async{
    try {
      var result = await WanAndroidRepository.queryArticle(page: currentPage, keywords: keywords.value);
      return result;
    }catch(e,s){
      handlerError(e, s);
      return null;
    }
  }

  /// 刷新数据
  onRefresh() async {
    currentPage = 0;
    PageBean<ArticleBean>? model = await loadData();
    if (model == null) {
      refreshController.refreshFailed();
      return;
    } else {
      refreshController.refreshCompleted();
    }
    if (model.over == true) {
      refreshController.loadNoData();
    }else{
      refreshController.loadComplete();
    }

    if (model.datas?.isNotEmpty == true) {
      articles.clear();
      articles.addAll(model.datas!);
      currentPage++;
      setIdle();
    }
  }

  onLoadMore() async {
    PageBean<ArticleBean>? model = await loadData();
    if (model == null) {
      refreshController.loadFailed();
      return;
    }
    if (model.over == true) {
      refreshController.loadNoData();
    } else {
      refreshController.loadComplete();
    }

    if (model.datas?.isNotEmpty == true) {
      articles.addAll(model.datas!);
      currentPage++;
      update();
    }
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }

}
